package com.cskaoyan.demo5.servlet;

import com.cskaoyan.demo5.common.CommonServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * /admin/storage/create 文件上传请求的处理
 * ----------------------------854373967199670287990498
 * Content-Disposition: form-data; name="file"; filename="banner.png"
 * Content-Type: image/png
 *
 * JFIF         ICC_PROFILE        0  mntrRGB
 *
 * 1. MultipartConfig注解
 * 2. request.getPart("name对应的值") → request.getPart("file")
 */
@MultipartConfig
@WebServlet("/admin/storage/*")
public class AdminStorageServlet extends CommonServlet {

    /**
     * Content-Disposition: form-data; name="file"; filename="banner.png"
     * Content-Type: image/png
     *
     * JFIF         ICC_PROFILE        0  mntrRGB
     * 上面的这个信息通过part对象来进行封装，通过Part提供的方法获得更进一步的信息
     */
    public void create(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //用于获取请求中的信息、并封装到一个part对象中
        Part part = request.getPart("file");

        String name = part.getName();
        String submittedFileName = part.getSubmittedFileName();
        String contentType = part.getContentType();
        long size = part.getSize();
/*        System.out.println(name);
        System.out.println(submittedFileName);
        System.out.println(contentType);
        System.out.println(size);*/

        //字节输入流
        InputStream inputStream = part.getInputStream();
        //输出路径
        String destPath="d:/app2";
        //保存文件的地址和名称
        File destFile = new File(destPath, submittedFileName);
        //字节输出流
        FileOutputStream outputStream = new FileOutputStream(destFile);
        //保存文件到指定的位置
        int length=0;
        byte[] bytes = new byte[1024];
        while ((length = inputStream.read(bytes)) != -1) {
            outputStream.write(bytes,0,length);
        }
        inputStream.close();
        outputStream.close();
    }

}
